import { useEffect, useRef } from 'react'
import { useSetState } from 'ahooks'
import draggable from '../draggable'

const SvPanel = ({ color, onChange }) => {
  const $el = useRef()

  const [state, setState] = useSetState({
    cursorTop: 0,
    cursorLeft: 0,
    background: 'hsl(0, 100%, 50%)'
  })

  useEffect(() => {
    const dragConfig = {
      drag: (event) => {
        handleDrag(event)
      },
      end: (event) => {
        handleDrag(event)
      }
    }
    draggable($el.current, dragConfig)
    update()
  }, [])

  useEffect(() => {
    const { background } = state
    const newBackground = 'hsl(' + color.get('hue') + ', 100%, 50%)'
    if (newBackground !== background) {
      update()
    }
  }, [color])

  const update = () => {
    const saturation = color.get('saturation')
    const value = color.get('value')
    let { width, height } = $el.current.getBoundingClientRect()
    if (!height) height = (width * 3) / 4
    setState({
      cursorLeft: (saturation * width) / 100,
      cursorTop: ((100 - value) * height) / 100,
      background: 'hsl(' + color.get('hue') + ', 100%, 50%)'
    })
  }

  const handleDrag = (event) => {
    const rect = $el.current.getBoundingClientRect()
    let left = event.clientX - rect.left
    let top = event.clientY - rect.top
    left = Math.max(0, left)
    left = Math.min(left, rect.width)
    top = Math.max(0, top)
    top = Math.min(top, rect.height)
    setState({
      cursorLeft: left,
      cursorTop: top,
      background: 'hsl(' + color.get('hue') + ', 100%, 50%)'
    })
    color.set({
      saturation: (left / rect.width) * 100,
      value: 100 - (top / rect.height) * 100
    })
    onChange(color)
  }

  const { cursorTop, cursorLeft, background } = state
  return (
    <div className="color-svpanel" style={{ backgroundColor: background }} ref={$el}>
      <div className="color-svpanel__white" />
      <div className="color-svpanel__black" />
      <div
        className="color-svpanel__cursor"
        style={{
          top: cursorTop + 'px',
          left: cursorLeft + 'px'
        }}
      >
        <div />
      </div>
    </div>
  )
}

export default SvPanel
